<script setup>
	import { ref, onMounted } from 'vue'
	import { useUserStore } from '@/store/userInfo'

	const userStore = useUserStore()
	const shopApi = uniCloud.importObject( 'shop' )

	// 店铺设置数据
	const settings = ref( {
		isOpen: false,
		autoAcceptOrder: false,
		minOrderAmount: '',
		deliveryRange: '',
		deliveryFee: '',
		openTime: '',
		closeTime: ''
	} )

	// 处理开关变化
	const handleSwitchChange = ( key, event ) => {
		settings.value[ key ] = event.detail.value
	}

	// 处理时间选择
	const handleTimeChange = ( key, event ) => {
		settings.value[ key ] = event.detail.value
		// 验证时间选择的合理性
		if (settings.value.openTime && settings.value.closeTime) {
			if (settings.value.openTime >= settings.value.closeTime) {
				uni.showToast( {
					title: '结束时间必须晚于开始时间',
					icon: 'none'
				} )
				if (key === 'openTime') {
					settings.value.openTime = ''
				} else {
					settings.value.closeTime = ''
				}
			}
		}
	}

	// 验证数字输入
	const validateNumber = (value, min = 0) => {
		const num = Number(value)
		return !isNaN(num) && num >= min
	}

	// 保存设置
	const saveSettings = async ( ) => {
		// 验证必填项
		if (!settings.value.openTime || !settings.value.closeTime) {
			uni.showToast( {
				title: '请设置营业时间',
				icon: 'none'
			} )
			return
		}

		// 验证数字输入
		if (!validateNumber(settings.value.minOrderAmount)) {
			uni.showToast( {
				title: '请输入有效的起送金额',
				icon: 'none'
			} )
			return
		}

		if (!validateNumber(settings.value.deliveryRange)) {
			uni.showToast( {
				title: '请输入有效的配送范围',
				icon: 'none'
			} )
			return
		}

		if (!validateNumber(settings.value.deliveryFee)) {
			uni.showToast( {
				title: '请输入有效的配送费',
				icon: 'none'
			} )
			return
		}

		try {
			uni.showLoading( {
				title: '保存中...'
			} )

			await shopApi.updateShopSettings( settings.value, userStore.userInfo.role[0] )

			uni.hideLoading( )
			uni.showToast( {
				title: '保存成功',
				icon: 'success'
			} )
			
			// 延迟返回
			setTimeout(() => {
				uni.navigateBack()
			}, 1500)
		} catch ( e ) {
			uni.hideLoading( )
			uni.showToast( {
				title: '保存失败',
				icon: 'none'
			} )
			console.error( '保存店铺设置失败:', e )
		}
	}

	// 获取设置
	const getSettings = async () => {
		try {
			uni.showLoading({
				title: '加载中...'
			})
			
			const result = await shopApi.getShopSettings(userStore.userInfo.role[0])
			if (result.errCode === 0) {
				settings.value = result.data
			} else {
				throw new Error(result.errMsg)
			}
			
			uni.hideLoading()
		} catch (e) {
			uni.hideLoading()
			uni.showToast({
				title: e.message || '获取设置失败',
				icon: 'none',
				duration: 2000
			})
			console.error('获取店铺设置失败:', e)
		}
	}

	onMounted( ( ) => {
		getSettings( )
	} )
</script>

<template>
	<view class="shop-settings">
		<view class="settings-container">
			<!-- 营业状态 -->
			<view class="settings-section">
				<view class="section-title">营业状态</view>
				<view class="section-content">
					<view class="switch-item">
						<text>店铺营业</text>
						<switch :checked="settings.isOpen" @change="handleSwitchChange('isOpen', $event)"
							color="#46b0fe" />
					</view>
					<view class="switch-item">
						<text>自动接单</text>
						<switch :checked="settings.autoAcceptOrder"
							@change="handleSwitchChange('autoAcceptOrder', $event)" color="#46b0fe" />
					</view>
				</view>
			</view>

			<!-- 配送设置 -->
			<view class="settings-section">
				<view class="section-title">配送设置</view>
				<view class="section-content">
					<view class="input-item">
						<text>起送金额</text>
						<input type="digit" v-model="settings.minOrderAmount" placeholder="请输入起送金额" />
					</view>
					<view class="input-item">
						<text>配送范围(公里)</text>
						<input type="digit" v-model="settings.deliveryRange" placeholder="请输入配送范围" />
					</view>
					<view class="input-item">
						<text>配送费</text>
						<input type="digit" v-model="settings.deliveryFee" placeholder="请输入配送费" />
					</view>
				</view>
			</view>

			<!-- 营业时间 -->
			<view class="settings-section">
				<view class="section-title">营业时间</view>
				<view class="section-content">
					<view class="time-item">
						<text>开始时间</text>
						<picker mode="time" :value="settings.openTime"
							@change="handleTimeChange('openTime', $event)">
							<view class="picker">
								{{ settings.openTime || '请选择' }}
								<uni-icons custom-prefix="iconfont" type="yuan-a-ArrowRight2" color="#ced4da"
									:size="20" />
							</view>
						</picker>
					</view>
					<view class="time-item">
						<text>结束时间</text>
						<picker mode="time" :value="settings.closeTime"
							@change="handleTimeChange('closeTime', $event)">
							<view class="picker">
								{{ settings.closeTime || '请选择' }}
								<uni-icons custom-prefix="iconfont" type="yuan-a-ArrowRight2" color="#ced4da"
									:size="20" />
							</view>
						</picker>
					</view>
				</view>
			</view>

			<!-- 保存按钮 -->
			<button class="save-btn" @tap="saveSettings">保存设置</button>
		</view>
	</view>
</template>

<style lang="scss" scoped>
	.shop-settings {
		min-height: 100vh;
		padding: 24rpx;
		background-color: $page-bg-color;

		.settings-container {
			.settings-section {
				margin-bottom: 24rpx;
				padding: 24rpx;
				background-color: #fff;
				border-radius: 16rpx;

				.section-title {
					margin-bottom: 24rpx;
					font-size: 32rpx;
					color: $text-font-color-1;
					font-weight: 600;
				}

				.section-content {

					.switch-item,
					.input-item,
					.time-item {
						display: flex;
						justify-content: space-between;
						align-items: center;
						padding: 24rpx 0;
						border-bottom: 2rpx solid $line-color-aux;

						&:last-child {
							border-bottom: none;
						}

						text {
							font-size: 28rpx;
							color: $text-font-color-2;
						}

						input {
							width: 200rpx;
							padding: 12rpx 24rpx;
							text-align: right;
							background-color: $page-bg-color;
							border-radius: 8rpx;
							font-size: 28rpx;
							color: $text-font-color-1;
						}

						.picker {
							display: flex;
							align-items: center;
							font-size: 28rpx;
							color: $text-font-color-1;

							.uni-icons {
								margin-left: 8rpx;
							}
						}
					}
				}
			}

			.save-btn {
				width: 100%;
				height: 88rpx;
				line-height: 88rpx;
				text-align: center;
				background-color: $brand-theme-color;
				color: #fff;
				font-size: 32rpx;
				border-radius: 44rpx;
				margin-top: 48rpx;

				&:active {
					opacity: 0.9;
				}
			}
		}
	}
</style>